//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.wsd.smartcarwasher.service;

import com.github.pagehelper.PageHelper;
import com.wsd.smartcarwasher.annotation.Log;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.CardDao;
import com.wsd.smartcarwasher.dao.CardRecordMapper;
import com.wsd.smartcarwasher.domain.*;
import com.wsd.smartcarwasher.util.DateUtil;
import com.wsd.smartcarwasher.util.ReturnUtil;
import com.wsd.smartcarwasher.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class CardService {
    private static final Logger logger = LoggerFactory.getLogger(CardService.class);
    @Autowired(required = false)
    private MachineService machineService;
    @Resource
    private OrderService orderService;
    @Resource
    private CardOrderService cardOrderService;
    @Resource
    private CardDao cardDao;
    @Resource
    private CardRecordMapper cardRecordDao;

    public CardService() {
    }

    public int addCard(Card card) {
        card.setStatus(1);
        int changeRows = this.cardDao.addCard(card);
        this.addOrUpdateServiceList(card);
        return changeRows;
    }

    public List<Card> queryAllCard() {
        List<Card> cardList = this.cardDao.queryAllCards();
        if (cardList == null) {
            return Collections.emptyList();
        } else {
            Iterator var2 = cardList.iterator();

            while(var2.hasNext()) {
                Card card = (Card)var2.next();
                this.queryMachineOfCard(card);
            }

            return cardList;
        }
    }

    //根据订单详情查询会员卡信息
    public Card queryCardInfo(Integer cardId)
    {
        return cardDao.queryCardByCardId(cardId);
    }
    public List<Card> queryAllCardPc(Integer Page,Integer PageSize) {
        PageHelper.startPage(Page,PageSize);
        List<Card> cardList = this.cardDao.queryAllCardPc();
        if (cardList == null) {
            return Collections.emptyList();
        } else {
            Iterator var2 = cardList.iterator();

            while(var2.hasNext()) {
                Card card = (Card)var2.next();
                this.queryMachineOfCard(card);
            }

            return cardList;
        }
    }
    /**
     * 查询最优惠的会员卡信息
     */
    public UserCardEntity queryDiscountCard(String userId,Integer serviceId,String machineId)
    {

        if(serviceId==1)
        {
            serviceId=0;
        }else if(serviceId==2)
        {
            serviceId=1;
        }else{
            serviceId=2;
        }
        List<UserCardEntity> cardEntities=this.cardDao.queryUserDiscountCards(userId,1,serviceId,machineId);
        if(!StringUtil.isNullOrEmpty(cardEntities))
        {
            //寻找快到期的
            UserCardEntity cardEntity=cardEntities.stream().sorted(Comparator.comparing(UserCardEntity::getValidDate).reversed()).collect(Collectors.toList()).get(0);
            logger.info("普通会员卡"+cardEntity);
            return cardEntity;
        }

        List<UserCardEntity> cardRateEntities=this.cardDao.queryUserDiscountCards(userId,2,serviceId,machineId);
        System.out.println("折扣会员卡"+cardRateEntities);
        if(!StringUtil.isNullOrEmpty(cardRateEntities))
        {
            BigDecimal initPrice=cardRateEntities.get(0).getCardRate();
            BigDecimal finalInitPrice = initPrice;
            cardRateEntities=cardRateEntities.stream().filter(s->s.getCardRate().compareTo(finalInitPrice)==0).collect(Collectors.toList());
            UserCardEntity couponRateEntity=cardRateEntities.stream().sorted(Comparator.comparing(UserCardEntity::getValidDate).reversed()).collect(Collectors.toList()).get(0);
            return couponRateEntity;
        }
        return null;
    }

    public CardOrder queryCardOrder(String  ucId)
    {

        return this.cardOrderService.queryOrderInfoByUcId(ucId);
    }

    private void queryMachineOfCard(Card card) {
        if (card != null && !StringUtils.isBlank(card.getAvailableMachines())) {
            card.setMachineList(this.machineService.queryMachineByIds(Arrays.asList(card.getAvailableMachines().split(","))));
        }
    }

    public int deleteCard(int id) {
        return this.cardDao.updateCardStatus(id, 102);
    }

    public int updateCard(Card card) {
        int changeRow = this.cardDao.updateCard(card);
        this.addOrUpdateServiceList(card);
        return changeRow;
    }

    private void addOrUpdateServiceList(Card card) {
        if (!CollectionUtils.isEmpty(card.getServiceList())) {
            Iterator var2 = card.getServiceList().iterator();

            while(var2.hasNext()) {
                WashServiceWithTimes service = (WashServiceWithTimes)var2.next();
                if(card.getType()==2){service.setTimes(999);}
                this.cardDao.addService(service, card.getId());
            }

        }
    }

    @Resource
    private SMSService smsService;

    @Resource
    private UserInfoService userInfoService;

    boolean bindCardToUser(String userId, int cardId, String ucId) {
        logger.info("开始绑定信息");
        Card card = this.cardDao.queryCardByCardId(cardId);
        if (card != null && !CollectionUtils.isEmpty(card.getServiceList())) {

            UserCard userCard = new UserCard(userId, card,ucId);
            CardRecordExample example=new CardRecordExample();
            example.createCriteria().andUcIdEqualTo(ucId);
            List<CardRecord> cardRecords=this.cardRecordDao.selectByExample(example);
            CardRecord cardRecord=new CardRecord();
            if(cardRecords.isEmpty())
            {
                cardRecord.setCardId(cardId);
                cardRecord.setCreateTime(new Date());
                cardRecord.setPayTimes(new Date());
                cardRecord.setUcId(ucId);
                cardRecord.setUserId(userId);
                this.cardRecordDao.insert(cardRecord);
            }else{
                cardRecord.setCardId(cardId);
                cardRecord.setCreateTime(new Date());
                cardRecord.setPayTimes(new Date());
                cardRecord.setUcId(ucId);
                cardRecord.setUserId(userId);
                cardRecord.setFirstTimes(null);
                cardRecord.setRefundTime(null);
                this.cardRecordDao.updateByExample(cardRecord,example);
            }

            boolean rs=this.cardDao.bindCardToUser(userCard)!=0;

            if(rs){
                UserInfo user =  userInfoService.findById(userId);
                if(null !=user && StringUtils.isNotBlank(user.getMobile())){
                    smsService.sendCardMSG(user.getMobile(),card.getName(),
                            DateUtil.format(userCard.getValidDate()),card.getPrice().doubleValue());
                }
            }
            return rs;
        } else {
            return false;
        }
    }

    /**
     * 测试会员卡 是否可以在本机器上使用
     * @param userCard
     * @param machineId
     * @return
     */
    public  boolean testUserCard(UserCard userCard,int machineId){
        Card car= cardDao.queryCardByCardId(userCard.getCardId());
        String []  machineIds =car.getAvailableMachines().split(",");
        return Arrays.asList(machineIds).contains(String.valueOf(machineId));
    }

    @Log("使用折扣会员卡")
    public void payByRateCard(String userId, OrderInfo orderInfo) {
        int cardId = orderInfo.getCardId();
        int serviceId = orderInfo.getServiceId();
        String ucId = orderInfo.getUcId();
        UserCard userCard = this.queryUserCardByServiceId(userId, cardId, serviceId, ucId);
        if (null != userCard) {
            boolean isPaySuccess = false;
            WashServiceWithTimes service = (WashServiceWithTimes) userCard.getServices().stream().filter((s) -> {
                return serviceId == s.getId();
            }).findFirst().orElse(null);
            //无限次数的会员卡就不要去操作数据库了
            if (service != null && service.getTimes() == -1) {
                isPaySuccess = true;
            } else {
                isPaySuccess = this.updateLeftTimesByUCId(userId, cardId, serviceId, ucId);
            }

        }
    }



    @Log("使用了会员卡")
    public ModelMap payByCard(String userId, OrderInfo orderInfo) {
        int cardId = orderInfo.getCardId();
        int serviceId = orderInfo.getServiceId();
        String ucId = orderInfo.getUcId();
        int machineId = orderInfo.getMachineId();
        UserCard userCard = this.queryUserCardByServiceId( userId, cardId, serviceId, ucId);
        if(null != userCard){
            boolean isPaySuccess =false;

            WashServiceWithTimes service = (WashServiceWithTimes)userCard.getServices().stream().filter((s) -> {
                return serviceId == s.getId();
            }).findFirst().orElse(null);
            //无限次数的会员卡就不要去操作数据库了
            if (service != null && service.getTimes() == -1) {
                isPaySuccess =true;
            }else{
                isPaySuccess = this.updateLeftTimesByUCId(userId, cardId, serviceId, ucId);
            }
            if (!isPaySuccess) {
                return ReturnUtil.Error(ResultState.PAY_BY_CARD_FAIL.getMsg());
            } else {
                this.orderService.payFinishOrder(orderInfo);
                return ReturnUtil.Success(ResultState.PAY_BY_CARD_SUCCESS.getMsg(), orderInfo);
            }
        }else{
            return ReturnUtil.Error(ResultState.USER_CARD_CAN_NO_USED.getMsg());
        }

        /*UserCard userCard = this.queryUserCard(userId, cardId);
        if (userCard != null && !CollectionUtils.isEmpty(userCard.getServices())) {
            WashServiceWithTimes service = (WashServiceWithTimes)userCard.getServices().stream().filter((s) -> {
                return serviceId == s.getId();
            }).findFirst().orElse(null);
            if (service != null && service.getTimes() != 0) {
                int leftTimes = service.getTimes() - 1;
                boolean isPaySuccess = this.updateLeftTimes(userId, cardId, serviceId, leftTimes, userCard.getValidDate());
                if (!isPaySuccess) {
                    return ReturnUtil.Error(ResultState.PAY_BY_CARD_FAIL.getMsg());
                } else {
                    this.orderService.payFinishOrder(orderInfo);
                    return ReturnUtil.Success(ResultState.PAY_BY_CARD_SUCCESS.getMsg(), orderInfo);
                }
            } else {
                return ReturnUtil.Error(ResultState.USER_CARD_CAN_NO_USED.getMsg());
            }
        } else {
            return ReturnUtil.Error(ResultState.USER_CARD_NOT_EXIST.getMsg());
        }*/
    }

    public boolean updateLeftTimes(String userId, int cardId, int serviceId, int leftTimes, Date validDate) {
        return this.cardDao.updateLeftTimes(userId, cardId, serviceId, leftTimes, validDate) != 0;
    }

    public UserCard queryUserCard(String userId, int cardId) {
        List<UserCard> userCard=this.cardDao.queryUserCard(userId, cardId);

        if(StringUtil.isNullOrEmpty(userCard))
        {
           return null;
        }
        return userCard.get(0);
    }


    public UserCard queryUserCardByServiceId(String userId, int cardId,int serviceId,String ucId) {
        return this.cardDao.queryUserCardByServiceId(userId, cardId,serviceId,ucId);
    }


    private boolean updateLeftTimesByUCId(String userId, int cardId,int serviceId,String ucId) {
        return this.cardDao.updateLeftTimesByUCId(userId, cardId,serviceId,ucId) != 0;
    }


    public Card queryCardByCardId(int cardId) {
        return this.cardDao.queryCardByCardId(cardId);
    }

    /**
     * 小程序查询用户会员卡
     * @param userId
     * @return
     */
    public List<UserCard> queryUserCards(String userId) {
        List<UserCard> cards = this.cardDao.queryUserCards(userId);
        if (cards == null) {
            cards = Collections.emptyList();
        }
        Iterator var3 = cards.iterator();
        while(var3.hasNext()) {
            UserCard userCard = (UserCard)var3.next();
            userCard.setCard(this.cardDao.queryCardByCardId(userCard.getCardId()));
            userCard.setCardOrder(cardOrderService.queryOrderInfoByUcId(userCard.getUcId()));
        }
        return cards;
    }

    /**
     * 小程序端删除用户会员卡
     * @param userId
     * @param ucId
     * @return
     */
    public int deleteUserCard(String userId, String ucId) {
        return  this.cardDao.deleteUserCard(userId,ucId);
    }

    /**
     * pc 端 会员卡订单退款
     * @param order
     * @return
     */
    public int rollBackUserCard(OrderInfo order) {
        return  this.cardDao.rollBackUserCard(order);
    }

    //会员卡退款
    public int rollUserCard(CardOrder order) {
        return  this.cardDao.rollUserCard(order);
    }

}


/*
package com.wsd.smartcarwasher.service;

import com.wsd.smartcarwasher.constans.Global;
import com.wsd.smartcarwasher.constans.ResultState;
import com.wsd.smartcarwasher.dao.CardDao;
import com.wsd.smartcarwasher.domain.Card;
import com.wsd.smartcarwasher.domain.OrderInfo;
import com.wsd.smartcarwasher.domain.WashServiceWithTimes;
import com.wsd.smartcarwasher.domain.UserCard;
import com.wsd.smartcarwasher.util.ReturnUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Lazy;
import org.springframework.ui.ModelMap;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

@org.springframework.stereotype.Service
public class CardService {
    private static final Logger logger = LoggerFactory.getLogger(CardService.class);

    @Resource
    private MachineService machineService;

    @Lazy
    @Resource
    private OrderService orderService;

    @Resource
    private CardDao cardDao;

    public int addCard(Card card) {
        card.setStatus(Global.CARD_STATUS_NORMAL);
        int changeRows = cardDao.addCard(card);
        if (CollectionUtils.isNotEmpty(card.getServiceList())) {
            cardDao.addServiceList(card.getServiceList(), card.getId());
        }
        return changeRows;
    }

    public List<Card> queryAllCard() {
        List<Card> cardList = cardDao.queryAllCards();
        if (cardList == null) {
            return Collections.emptyList();
        }
        for (Card card : cardList) {
            queryMachineOfCard(card);
        }
        return cardList;
    }

    private void queryMachineOfCard(Card card) {
        if (card == null || StringUtils.isBlank(card.getAvailableMachines())) {
            return;
        }
        card.setMachineList(machineService.queryMachineByIds(Arrays.asList(card.getAvailableMachines().split(","))));
    }

    public int deleteCard(int id) {
        return cardDao.updateCardStatus(id, Global.CARD_STATUS_DELETE);
    }

    public int updateCard(Card card) {
        int changeRow = cardDao.updateCard(card);
        if (CollectionUtils.isNotEmpty(card.getServiceList())) {
            cardDao.addServiceList(card.getServiceList(), card.getId());
        }
        return changeRow;
    }

    public boolean bindCardToUser(String userId, int cardId) {
        Card card = cardDao.queryCardByCardId(cardId);
        if (card == null || CollectionUtils.isEmpty(card.getServiceList())) {
            return false;
        }
        UserCard userCard = new UserCard(userId, card);
        UserCard oldUserCard = queryUserCard(userId, cardId);
        if (oldUserCard == null) {
            return cardDao.bindCardToUser(userCard) != 0;
        } else {
            List<WashServiceWithTimes> newService = userCard.getServices();
            for (WashServiceWithTimes service : newService) {
                WashServiceWithTimes oldService = oldUserCard.getServices().stream()
                        .filter(s -> service.getId() == s.getId()).findFirst().get();
                int leftTimes = oldService.getTimes() + service.getTimes();
                boolean updateSuccess = updateLeftTimes(userId, cardId, service.getId(), leftTimes);
                if (!updateSuccess) {
                    logger.error("更新用户会员卡服务剩余次数失败，userId=" + userId
                            + ",cardId=" + cardId + ",serviceId=" + service.getId() + ",leftTimes=" + leftTimes);
                }
            }
        }
        return true;
    }

    public ModelMap payByCard(String userId, OrderInfo orderInfo) {
        int cardId = orderInfo.getCarId();
        int serviceId = orderInfo.getServiceId();
        UserCard userCard = queryUserCard(userId, cardId);
        if (userCard == null || CollectionUtils.isEmpty(userCard.getServices())) {
            return ReturnUtil.Error(ResultState.USER_CARD_NOT_EXIST.getMsg());
        }
        WashServiceWithTimes service = userCard.getServices().stream().filter(s -> serviceId == s.getId()).findFirst().orElse(null);
        if (service == null || service.getTimes() == 0) {
            return ReturnUtil.Error(ResultState.USER_CARD_CAN_NO_USED.getMsg());
        }
        int leftTimes = service.getTimes() - 1;
        boolean isPaySuccess = updateLeftTimes(userId, cardId, serviceId, leftTimes);
        if (!isPaySuccess) {
            return ReturnUtil.Error(ResultState.PAY_BY_CARD_FAIL.getMsg());
        }
        orderService.payFinishOrder(orderInfo);
        return ReturnUtil.Success(ResultState.PAY_BY_CARD_SUCCESS.getMsg(), orderInfo);
    }



    private boolean updateLeftTimes(String userId, int cardId, int serviceId, int leftTimes) {
        return cardDao.updateLeftTimes(userId, cardId, serviceId, leftTimes) != 0;
    }

    private UserCard queryUserCard(String userId, int cardId) {
        return cardDao.queryUserCard(userId, cardId);
    }

    public Card queryCardByCardId(int cardId) {
        return cardDao.queryCardByCardId(cardId);
    }

    public List<UserCard> queryUserCards(String userId) {
        List<UserCard> cards = cardDao.queryUserCards(userId);
        if (cards == null) {
            cards = Collections.emptyList();
        }
        for (UserCard userCard : cards) {
            userCard.setCard(cardDao.queryCardByCardId(userCard.getCardId()));
        }
        return cards;
    }
}
*/
